<?php
class Api_DbTable_News extends Core_Db_Table_Abstract implements Core_Db_Crud_Interface {
	protected $_name = 'news';
	protected $_rowClass = 'Api_Row_News';
	
	public function last() {
		return $this->fetchAll ( $this->select ()->limit ( 5 )->order ( 'date DESC' ) );
	}
	
	public function all() {
		$result = array ();
		foreach ( $this->fetchAll ( $this->select ()->order ( 'date DESC' ) ) as $key => $val )
			$result [$key] = $val->toArray ();
		return $result;
	}
	
	public function getAll($parent = null) {
		return $this->fetchAll ( $this->select () );
	}
	
	public function getBackUrl($id, $type = 0) {
		if ($type === 0)
			return null;
		return Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( array ("controller" => "admin", "action" => "read", "name" => "news" ), null, true );
	}
	
	public function getMetaData($id) {
		return array ('title', 'descript', 'date' );
	}
	
	public function getOne($id) {
		$r = $this->find ( $id );
		$zd = new Zend_Date ( $r [0] ['date'] );
		$r [0] ['date'] = $zd->toString ( 'MM/dd/yyyy' );
		return $r [0];
	}
	public function getForm($id, $req = true) {
		return new Api_Form_News ();
	}
	
	public function create(Zend_Form $form, $parent = 0) {
		$data = $form->getValues ();
		
		if (isset ( $data ['date'] )) {
			$zd = new Zend_Date ( $data ['date'] );
			$data ['date'] = $zd->getTimestamp ();
		} else
			$data ['date'] = time ();
		
		$this->insert ( $data );
	}
	public function edit(Zend_Form $form, $id) {
		$data = $form->getValues ();
		if (isset ( $data ['date'] )) {
			$zd = new Zend_Date ( $data ['date'] );
			$data ['date'] = $zd->getTimestamp ();
		}
		$this->update ( $data, 'id = ' . $id );
	}
	public function remove($id) {
		$this->delete ( 'id = ' . $id );
	}
}